#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <network/dual_stack_socket.h>

int main(int argc, char** argv)
{
    char buf[1024] = {0};
    int slen = 0;

    char* addr = "::1";
    int port = 11024;
    sockaddr_storage cliaddr;
    int cliaddrlen = 0;
    int clisocket;

    if (argc >= 3)
    {
        addr = argv[1];
        port = atoi(argv[2]);
    }

    dualstack_socket_t s = create_dual_socket(addr, port, protocol_type_tcp);

    if (!s)
    {
        printf("Create socket failed!\n");
        exit(1);
    }
    printf("Create socket succeed!\n");

    if (bind(get_socket_fd(s), get_sockaddr(s), get_sockaddr_len(s))==-1)
    {
        printf("bind failed!\n");
        exit(1);
    }
    printf("Bind succeed!\n");

    if (listen(get_socket_fd(s), 100) < 0)
    {
        printf("listen() failed");
        exit(1);
    }
    printf("Listen succeed!\n");


    slen = get_sockaddr_len(s);
    for (;;) /* Run forever */
    {
        /* Set the size of the in-out parameter */
        cliaddrlen = sizeof(cliaddr);

        /* Wait for a client to connect */
        if ((clisocket = accept(get_socket_fd(s), (struct sockaddr*) &cliaddr,
                                (socklen_t* __restrict__)&cliaddrlen)) < 0)
        {
            printf("accept() failed");
            exit(1);
        }
        printf("accept succeed!\n");

        /* clntSock is connected to a client! */

        // printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));

        // HandleTCPClient(clntSock);
        while(recv(clisocket, buf, 1023, 0) > 0)
        {
            printf("%s\n", buf);
        }

        close(clisocket);
    }
    printf("Recv Ok!\n");
    destroy_dual_socket(s);
    return 0;
}

